import 'package:flutter/material.dart';
import 'api_service.dart';
import 'user_response.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'FastAPI Flutter Demo',
      home: UserFormPage(),
    );
  }
}

class UserFormPage extends StatefulWidget {
  @override
  _UserFormPageState createState() => _UserFormPageState();
}

class _UserFormPageState extends State<UserFormPage> {
  final _nameController = TextEditingController();
  final _ageController = TextEditingController();
  String? _responseMessage;

  Future<void> _submit() async {
     try {
    final name = _nameController.text;
    final age = int.tryParse(_ageController.text) ?? 0;

    final response = await ApiService.sendUserData(name, age);
    setState(() {
      _responseMessage = response?.message ?? '请求失败';
      print("✅ 响应内容：$_responseMessage");
    });
  } catch (e, stack) {
    print("⚠️ 捕获异常: $e");
    print("📌 堆栈信息: $stack");
    setState(() {
      _responseMessage = '出错了：$e';
    });
  }
}
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('提交信息')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(controller: _nameController, decoration: InputDecoration(labelText: '姓名')),
            TextField(controller: _ageController, decoration: InputDecoration(labelText: '年龄'), keyboardType: TextInputType.number),
            SizedBox(height: 20),
            ElevatedButton(onPressed: _submit, child: Text('提交')),
            if (_responseMessage != null) ...[
              SizedBox(height: 20),
              Text('服务器响应：$_responseMessage'),
            ]
          ],
        ),
      ),
    );
  }
}